package com.citusdata.elven.linearRoad;

import java.lang.Comparable;


// Helper class to convert between segment and position numbers.
class ConversionUtil {
  private static final int POSITIONS_IN_SEGMENT = 5280; 

  public static int posToSeg(int pos) {
    // In an inexact integer division, Java rounds the result down.
    return (pos/POSITIONS_IN_SEGMENT);
  }

  public static int segBeginToPos(int seg) {
    return (seg*POSITIONS_IN_SEGMENT);
  }

  public static int segEndToPos(int seg) {
    // Returns 1 position past the end of segment
    return ((seg+1)*POSITIONS_IN_SEGMENT);
  }
}


// Helper class to keep position information for a vehicle.
class FullPosition implements Comparable {
  private final int expressway;
  private final int direction;
  private final int position;

  public FullPosition(int xway, int dir, int pos) {
    expressway = xway;
    direction = dir;
    position = pos;
  }

  public boolean equals(Object obj) {
    if (!(obj instanceof FullPosition)) {
      return false;
    }
    FullPosition pos = (FullPosition) obj;
    return (pos.expressway == expressway) && (pos.direction == direction) &&
           (pos.position == position);
  }

  public int compareTo(Object obj) {
    FullPosition pos = (FullPosition) obj;

    assert (expressway >= 0) && (direction >= 0) && (position >= 0);
    assert (pos.expressway >= 0) && (pos.direction >= 0) && (pos.position >= 0);

    int expresswayDiff = expressway - pos.expressway;
    if (expresswayDiff != 0) {
      return expresswayDiff;
    }

    int directionDiff = direction - pos.direction;
    if (directionDiff != 0) {
      return directionDiff;
    }

    return (position - pos.position);
  }

  public int hashCode() {
    int result = 17;
    result = 37*result + expressway;
    result = 37*result + direction;
    result = 37*result + position;
    return result;
  }

  public boolean sameSegment(FullPosition pos) {
    return (pos.expressway == expressway) && (pos.direction == direction) &&
           (ConversionUtil.posToSeg(pos.position) == 
            ConversionUtil.posToSeg(position));
  }
}
